package com.ruoyi.feike.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.AnnualReviewy;
import com.ruoyi.feike.domain.Fileupload;
import com.ruoyi.feike.domain.ParkingLocationRegistration;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.mapper.AnnualReviewyMapper;
import com.ruoyi.feike.mapper.ParkingLocationRegistrationMapper;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IFileuploadService;
import com.ruoyi.feike.service.IParkingLocationRegistrationService;
import com.ruoyi.feike.service.IParkingLocationService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.*;

/**
 * feikeController
 *
 * @author ruoyi
 * @date 2022-08-02
 */
@RestController
@RequestMapping("/feike/registration")
@Slf4j
public class ParkingLocationRegistrationController extends BaseController
{
    @Autowired
    private IParkingLocationRegistrationService parkingLocationRegistrationService;

    @Autowired
    private IParkingLocationService parkingLocationService;

    @Autowired
    private IFileuploadService fileuploadService;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private ParkingLocationRegistrationMapper parkingLocationRegistrationMapper;

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:list')")
    @GetMapping("/list")
    public TableDataInfo list(ParkingLocationRegistration parkingLocationRegistration)
    {
        startPage();
        List<ParkingLocationRegistration> list = parkingLocationRegistrationService.selectParkingLocationRegistrationList(parkingLocationRegistration);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(AnnualReviewy annualReviewy, ParkingLocationRegistration parkingLocationRegistration)
    {
        startPage();
        List<AnnualReviewyHistoryVO> list = parkingLocationRegistrationService.selectParkingLocationRegistrationListAll(annualReviewy,parkingLocationRegistration);
        return getDataTable(list);
    }

    /**
     * 导出feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:export')")
    @Log(title = "feike", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ParkingLocationRegistration parkingLocationRegistration)
    {
        List<ParkingLocationRegistration> list = parkingLocationRegistrationService.selectParkingLocationRegistrationList(parkingLocationRegistration);
        ExcelUtil<ParkingLocationRegistration> util = new ExcelUtil<ParkingLocationRegistration>(ParkingLocationRegistration.class);
        return util.exportExcel(list, "registration");
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(parkingLocationRegistrationService.selectParkingLocationRegistrationById(id));
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:query')")
    @GetMapping(value = "/ByInstanceId/{instanceId}")
    public AjaxResult getInfoByInstanceId(@PathVariable("instanceId") String instanceId)
    {
        return AjaxResult.success(parkingLocationRegistrationService.selectParkingLocationRegistrationByInstanceId(instanceId));
    }

    /**
     * 查询 h_parking_location 列表信息
     */
    @GetMapping("/getList")
    public TableDataInfo getList()
    {
        startPage();
        List<Map> list = parkingLocationService.selectParkingLocationLists();
        return getDataTable(list);
    }

    /**
     *
     * @return
     */
    @PostMapping("/getFlagByDealerNameAndType")
    public AjaxResult getFlagByDealerNameAndType(@RequestBody Map map)
    {
        return AjaxResult.success(parkingLocationService.getFlagByDealerNameAndType(map));
    }

    /**
     * 根据group和dealer获取详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:query')")
    @PostMapping(value = "/getInfoGroupAndDealer")
    public AjaxResult getInfoByGroupIdAndDealerId(@RequestBody Map<String,Object> map)
    {
        return AjaxResult.success(parkingLocationRegistrationService.selectParkingLocationRegistration(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map)
    {
        return toAjax(parkingLocationRegistrationService.insertParkingLocationRegistrationMap(map));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ParkingLocationRegistration parkingLocationRegistration,@RequestBody Map<String,Object> map)
    {
        System.out.println("ParkingLocationRegistration修改=="+map);
        if(null != map.get("instanceId")){
            AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId((String) map.get("instanceId"));
            Task task = null;
            String instanceId = map.get("instanceId").toString();
        if (map.get("caoGao") != null && map.get("caoGao").toString().equals("0")) { //草稿接口非保存，提交流程
            Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                    .getUser()
                    .getUserId()
                    .toString());
            String title = "";
            if (StringUtils.isNotNull(map.get("name"))) {
                title = String.valueOf(map.get("name"));
            } else {
                title = "Annual Review";
            }

            //流程开始
            ProcessInstance processInstance = null;
            if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(map.get("processDefinitionKey")+"")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            } else {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("annualVerification")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            }


            task = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .singleResult();
            TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
            List<Task> todoList = query.list();//获取申请人的待办任务列表
            for (Task tmp : todoList) {
                if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                    task = tmp;//获取当前流程实例，当前申请人的待办任务
                    break;
                }
            }
            HashMap<String, Object> variables = new HashMap<String, Object>();
            List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
            if(CollectionUtil.isNotEmpty(actForm)){
                for (Map<String, Object> form : actForm) {
                    variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
                }
            }

            variables.put("toUnderwriter", 0);


            taskService.complete(task.getId(), variables);

            if(ObjectUtil.isNotEmpty(task)){
                annualReviewy.setStartNode(task.getName());
            }
        }

        Map<String, Object> dataMap = objectToMap(parkingLocationRegistration);
        List<ParkingLocationRegistration> registrationList = (List<ParkingLocationRegistration>)map.get("form");
        String s = JSONUtil.toJsonStr(registrationList);
        registrationList = JSONUtil.toList(s,ParkingLocationRegistration.class);

        Set set = dataMap.keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext();) {
            Object obj = (Object) iterator.next();
            Object value =(Object)map.get(obj);
            remove(value, iterator);
        }
        System.out.println("ParkingLocationRegistration修改=="+dataMap);
        if(dataMap.get("id")!=null){
            dataMap.remove("id");
        }


        if(dataMap.size()>=1 && CollectionUtil.isNotEmpty(registrationList)){
            for (ParkingLocationRegistration registration : registrationList) {
                if(ObjectUtil.isNotEmpty(registration.getParkinglocations())){
                    registration.setProvince(registration.getParkinglocations()[0]);
                    registration.setCity(registration.getParkinglocations()[1]);
                    registration.setCounty(registration.getParkinglocations()[2]);
                }
                ParkingLocationRegistration parkingLocationRegistration1 = parkingLocationRegistrationService.selectParkingLocationRegistrationByid(registration.getId());
                parkingLocationRegistrationService.updateParkingLocationRegistration(registration);
                annualReviewyService.saveDbLog("3","修改表单","修改Parking Location Registration表单信息",instanceId,parkingLocationRegistration1,registration,null);


                // 保存上传文件到数据库中
                List<Fileupload> uploadFile = registration.getUploadFile();
                if(CollectionUtil.isNotEmpty(uploadFile)){
                    for (Fileupload fileupload : uploadFile) {
                        if(StringUtils.isEmpty(fileupload.getId())){
                            fileupload.setId(IdUtils.simpleUUID());
                            fileupload.setInstanceId(registration.getId());
                            fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                            fileupload.setCreateName(SecurityUtils.getNickName());
                            fileupload.setCreateTime(new Date());
                            fileupload.setOriginalFileName(fileupload.getName());
                            fileupload.setType("parkingLocationRegistration");
                            fileuploadService.insertFileupload(fileupload);
                            annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }
            //return toAjax(parkingLocationRegistrationService.updateParkingLocationRegistration(registrationList.get(0)));
        }


            //检查是否是从草稿处进行提交 是则 AnnualReviewy状态改回0
            if (map.get("caoGao") != null && map.get("caoGao").toString().equals("0")) {
                annualReviewy.setState("0");
            }
            String UpdateBy = annualReviewy.getUpdateBy();
            if(null != UpdateBy){
                annualReviewy.setUpdateBy(UpdateBy +"|"+ SecurityUtils.getUsername());
            }else{
                annualReviewy.setUpdateBy(SecurityUtils.getUsername());
            }
            annualReviewy.setLockname(null);

            annualReviewyMapper.updateAnnualReviewy(annualReviewy);

            if(map.get("caoGao") != null && map.get("caoGao").toString().equals("0")){
                //发送邮件
                try {
                    org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                            .processInstanceId(task.getProcessInstanceId())
                            .singleResult();
                    // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                    org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                            .processInstanceId(processInstanceMe.getProcessInstanceId())
                            .singleResult();

                    ThreadUtil.execute(new Runnable() {

                        @Override
                        public void run() {
                            actTaskService.sendMail(task1, instanceId,null);
                        }
                    });

                } catch (Exception e) {
                    log.error("邮件发送失败，{}",e.getMessage());
                }
            }



            return AjaxResult.success();
        }else {
            return AjaxResult.error("流程ID缺失");
        }
    }

    /**
     * 删除feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(parkingLocationRegistrationService.deleteParkingLocationRegistrationByIds(ids));
    }

    /**
     * 删除数据库文件
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteFile/{id}")
    public AjaxResult deleteFile(@PathVariable String id)
    {
        if(StringUtils.isEmpty(id)){
            return AjaxResult.error("ID不能为空");
        }
        return toAjax(fileuploadService.deleteFileuploadById(id));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:registration:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/getVimInfo")
    public AjaxResult getVimInfo(@RequestBody Map<String,Object> map)
    {
        return toAjax(parkingLocationRegistrationService.insertParkingLocationRegistrationMap(map));
    }

    /**
     * 查vin下拉列表数据
     */
    @PostMapping("/vinlist")
    public AjaxResult vinlist(@RequestBody Map<String, Object> map){
        return AjaxResult.success(parkingLocationRegistrationService.vinlist(map));
    }
    public static Map<String, Object> objectToMap(Object object){
        Map<String,Object> dataMap = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                field.setAccessible(true);
                dataMap.put(field.getName(),field.get(object));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return dataMap;
    }

    private static void remove(Object obj,Iterator iterator){
        if(obj instanceof String){
            String str = (String)obj;
            if(StringUtil.isEmpty(str)){
                iterator.remove();
            }
        }else if(obj instanceof Collection){
            Collection col = (Collection)obj;
            if(col==null||col.isEmpty()){
                iterator.remove();
            }

        }else if(obj instanceof Map){
            Map temp = (Map)obj;
            if(temp==null||temp.isEmpty()){
                iterator.remove();
            }

        }else if(obj instanceof Object[]){
            Object[] array =(Object[])obj;
            if(array==null||array.length<=0){
                iterator.remove();
            }
        }else{
            if(obj==null){
                iterator.remove();
            }
        }
    }

}
